package latisi.models {
  import org.restfulx.collections.ModelsCollection;
  import org.restfulx.Rx;
  import org.restfulx.serializers.*;  
  import org.restfulx.models.RxModel;
  import mx.collections.ArrayCollection;
  import com.adobe.serialization.json.JSON;

  [Resource(name="tblocks")]
  [Bindable]
  public class Tblock extends RxModel {
    public static const LABEL:String = "classification";

    public var classification:String = "";

    public var mlClass:String = "";

    public var avgh:int = 0;

    public var format:String = "";

    public var h:int = 0;

    public var p:int = 0;

    public var tbid:int = 0;

    public var s:String = "";

    public static var sectionNamesAC:ArrayCollection;

    [BelongsTo]
    public var article:Article;

    [BelongsTo]
    public var page:Page;

    [HasOne]
    public var nfRect:NfRect;
    
    [HasMany]
    public var words:ModelsCollection;
    
    public function Tblock() {
      super(LABEL);
    }

    public function merge(tb:Tblock):Tblock {
      var newTb:Tblock = new Tblock();
      newTb.p = p;
      newTb.article = article;
      newTb.page = page;

      if (classification == tb.classification) {
      	newTb.classification = tb.classification;
      }
      newTb.tbid = -1; // should be set to (max tbid + 1)
      newTb.nfRect = new NfRect();
      // create new rectangle
      if (nfRect.x < tb.nfRect.x) {
      	newTb.nfRect.x = nfRect.x;
      } else {
      	newTb.nfRect.x = tb.nfRect.x;
      }
      if (nfRect.y < tb.nfRect.y) {
      	newTb.nfRect.y = nfRect.y;
      } else {
      	newTb.nfRect.y = tb.nfRect.y;
      }
      var selfMaxX:int;
      var tbMaxX:int;
      selfMaxX = nfRect.x + nfRect.width;
      tbMaxX = tb.nfRect.x + tb.nfRect.width;
      if (selfMaxX < tbMaxX) {
      	newTb.nfRect.width = tbMaxX - newTb.nfRect.x;
      } else {
      	newTb.nfRect.width = selfMaxX - newTb.nfRect.x;
      }
      var selfMaxY:int;
      var tbMaxY:int;
      selfMaxY = nfRect.y + nfRect.height;
      tbMaxY = tb.nfRect.y + tb.nfRect.height;
      if (selfMaxY < tbMaxY) {
      	newTb.nfRect.height = tbMaxY - newTb.nfRect.y;
      } else {
      	newTb.nfRect.height = selfMaxY - newTb.nfRect.y;
      }
      newTb.create({recursive: true});
      return newTb;
    }

    public static function sectionNames():void {
      var url:String = "/tblocks/section_names.json";
      Rx.http({
	onResult: sectionNamesResult,
	    rootUrl: "http://0.0.0.0:3000",
	    serializer: new JSONSerializer,
	    resultFormat: "text"
	    }).invoke({URL: url, unmarshall: false});
    }

    private static function sectionNamesResult(result:Object):void {
      var vo:Object = JSON.decode(result as String);
      sectionNamesAC = new ArrayCollection(vo as Array);
    }
  }
}
